<?php
/**
 * Created by 分销类.
 * User: 尚金殿
 * Date: 2018/9/6
 * Time: 16:36
 */

namespace app\app\controller\v1;


use app\app\util\OnlineUtils;
use think\Db;

class DistributionController extends BaseController
{

    //分销
    public function findUserFather($id,$order_id)
    {
        if (!$id || !is_numeric($id)) {
            return show(0, '用户ID不能为空');
        }
        //获取订单ID
        if (!$order_id || !is_numeric($order_id)) {
            return show(0, '订单ID不能为空');
        }


        //获取当前用户的信息
        $user = Db::name('user')->where('id', $id)->field('id,tid')->find();
        //获取订单信息
        $order = Db::name('order')->alias('o')->join('t_line l', 'o.ware_id = l.id')->where('o.order_id', $order_id)->find();

        $items = [];
        if ($user['tid'] != 0) {
            //查找二级
            $father2 = Db::name('user')->where('id', $user['tid'])->field('id,tid')->find();

            $items['father2'] = $father2;

            if ($father2['tid'] != 0) {
                //查找一级
                $father1 = Db::name('user')->where('id', $father2['tid'])->field('id,tid')->find();
                $items['father1'] = $father1;
            }
        }

        //循环付款和存储数据
        //获取分销比例
        $system = Db::name('system')->where('id',1)->find();
        if ($items) {
            //有父级的
            if (count($items) == 1) {

                $res = $this->distributionRecords($items['father2']['id'], $order_id, $order['ware_price'], $system['one_member']);
                $res ? true : false;
            } else if (count($items) == 2) {

                $res2 = $this->distributionRecords($items['father2']['id'], $order_id, $order['ware_price'], $system['two_member']);
                $res1 = $this->distributionRecords($items['father1']['id'], $order_id, $order['ware_price'], $system['one_member']);

                if($res2 || $res1){
                    return show(1,'OK');
                }

            }
        }

    }

    //分销记录
    public function recordsByUserId(){
        $user_id = OnlineUtils::getUserIdBySid();
        if(!$user_id){
            return show(0,'用户ID不能为空');
        }

        $res = Db::name('distribution_records')->alias('d')->join('t_order o','d.order_id = o.order_id')->join('t_user u','o.user_id = u.id')->join('t_line l','o.ware_id = l.id')->where('d.user_id = '.$user_id)->field('o.order_id,o.order_code,u.id,u.avatar_url,d.price,o.ware_price,l.title,u.nickname')->paginate(7);
        if(!$res){
            return show(0,'没有分销记录');
        }
        return show(1,'OK',$res);

    }



    //付款到余额并储存分销记录
    public function distributionRecords($user_id,$order_id,$price,$dis){
        //入库储存
        $res = array(
            'user_id' => $user_id,
            'order_id' => $order_id,
            'price' => $price * $dis / 100,
            'create_time' => time(),
        );

        //入库
        $recordsId = Db::name('distribution_records')->insertGetId($res);
        if(!$recordsId){
            return false;
        }
        //在父级余额里面新增
        $oneUser = Db::name('user')->where('id',$user_id)->find();
        $result['balance'] = $oneUser['balance'] + $res['price'];
        //修改父级余额
        $id = Db::name('user')->where('id',$oneUser['id'])->update($result);
        if(!$id){
            return false;
        }
        return true;

    }









    //企业付款
    public function compantPayment($user_id,$order_id){
        //支付信息
        $AppId = config('MCH_APPID');
        $MCH_ID = config('MCH_ID');
        $KEY = config('WX_APP_KEY');
        //获取用户信息
        $user = Db::name('user')->where('id',$user_id)->find();

        //获取订单信息
        $order = Db::name('order')->alias('o')->join('t_line l','o.ware_id = l.id')->where('o.order_id',$order_id)->find();

        $refundCode = OnlyOneOrderNumber(); //退款订单号
        //拼接数据
        $webData = array(
            'mch_appid' => $AppId,//商户账号appid
            'mchid'     => $MCH_ID,//商户号
            'nonce_str' => md5(time()),//随机字符串
            'partner_trade_no'=> $refundCode, //商户订单号，需要唯一
            'openid' => $user['open_id'],//转账用户的openid
            'check_name'=> 'NO_CHECK', //OPTION_CHECK不强制校验真实姓名, FORCE_CHECK：强制 NO_CHECK：
            'amount' => $order['ware_price'] * 100, //付款金额单位为分
            'desc'   => '[啊哈旅游]分销',//企业付款描述信息
            'spbill_create_ip' => $this->request->ip(),//获取IP

        );

        //将数组用&连接起来
        foreach($webData as $k => $v){
            $tarr[] = $k.'='.$v;
        }

        sort($tarr);
        $sign = implode($tarr, '&');
        $sign .= '&key='.$KEY;
        $webData['sign']=strtoupper(md5($sign));
        $wget = $this->arrToXml($webData);//数组转XML
        $pay_url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';//api地址
        $res = $this->postData($pay_url,$wget);//发送数

        if(!$res){
            return show(0,'Can\'t connect the server');
        }

        $content = simplexml_load_string($res, 'SimpleXMLElement', LIBXML_NOCDATA);

        if(strval($content->return_code) == 'FAIL'){
            return show(0,strval($content->return_msg));
        }
        if(strval($content->result_code) == 'FAIL'){
            return show(0, strval($content->err_code),':'.strval($content->err_code_des));
        }
        $rdata = array(
            'mch_appid'        => strval($content->mch_appid),
            'mchid'            => strval($content->mchid),
            'device_info'      => strval($content->device_info),
            'nonce_str'        => strval($content->nonce_str),
            'result_code'      => strval($content->result_code),
            'partner_trade_no' => strval($content->partner_trade_no),
            'payment_no'       => strval($content->payment_no),
            'payment_time'     => strval($content->payment_time),
        );
        return $rdata;

    }

    //将数组转化成xml
    public function arrToXml($arr){
        if(!is_array($arr) || count($arr) == 0) return '';
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;

    }


    //请求curl
    public function postData($url,$fields){
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = false; //是否返回响应头信息
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $fields;
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        //以下是证书相关代码
        $params[CURLOPT_SSLCERTTYPE] = 'PEM';
        $params[CURLOPT_SSLCERT] = getcwd().'/weixin/cert/apiclient_cert.pem';//绝对路径
        $params[CURLOPT_SSLKEYTYPE] = 'PEM';
        $params[CURLOPT_SSLKEY] = getcwd().'/weixin/cert/apiclient_key.pem';//绝对路径

        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
        curl_close($ch); //关闭连接
        return $content;

    }
}